﻿using System;
using System.Collections.Generic;
using System.Text;

namespace AutoUpdateService.Mgr.Handler
{
    using System.IO;
    using System.Linq;
    using AutoUpdate.Model.Packet;
    public class getNewestVersionHandler : Handler
    {
        public getNewestVersionHandler()
        {
            this.name = "getNewestVersion";
        }

        public override void doAction(Packet packet)
        {
            if (packet != null)
            {
                string versionFile = Environment.CurrentDirectory + "\\" + ConfigMgr.getInstance().config.versionPath + "\\version.ini";

                string value = File.ReadAllText(versionFile, Encoding.UTF8);

                List<AutoUpdate.Model.Model.fileTransfer.fs_version> versionList = null;

                if (!string.IsNullOrEmpty(value))
                {
                    versionList = AutoUpdate.Utility.Helper.JsonHelper.getObject<List<AutoUpdate.Model.Model.fileTransfer.fs_version>>(value);
                }


                if (versionList != null)
                {
                    if (versionList.Count > 0)
                    {
                        AutoUpdate.Model.Model.fileTransfer .fs_version version = versionList.OrderByDescending(a => a.createTime).ToList()[0];

                        AutoUpdate.Model.Packet.ResponsePacket response = new ResponsePacket();

                        packet.FillData(response);

                        response.PacketType = PacketType.Response;

                        response.MessageContent = Newtonsoft.Json.JsonConvert.SerializeObject(version);

                        ClientMgr.getInstance().transferMessage(response);
                    }
                }
            }
        }
    }
}
